package com.markerhub.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.markerhub.common.dto.CourseDTO;
import com.markerhub.common.vo.CourseVO;
import com.markerhub.common.vo.StudentVO;
import com.markerhub.entity.Course;
import com.markerhub.entity.ManagerActivity;
import com.markerhub.entity.ManagerClass;
import com.markerhub.mapper.CourseMapper;
import com.markerhub.mapper.ManagerActivityMapper;
import com.markerhub.mapper.ManagerClassMapper;
import com.markerhub.service.CourseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;



@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {
@Autowired
CourseMapper courseMapper;
@Autowired
    ManagerActivityMapper activityMapper;
@Autowired
    ManagerClassMapper classMapper;
    @Override
    public IPage getCourses(String activityName, String courseName, String status, String teacherName, int currentPage, int pageSize) {
        Page<Course> page = new Page<>(currentPage, pageSize);

        Integer countCourses = courseMapper.countCourses(activityName, courseName, status, teacherName);
        IPage<Course> courseIPage = courseMapper.getCourses(page, activityName, courseName, status, teacherName);
        return courseIPage;
    }

    @Override
    public IPage<CourseVO> getTeacherCourses(Long teacherId, Integer currentPage, Integer pageSize,
                                             String courseName, String status, String activityName) {
        Page<Course> page = new Page<>(currentPage, pageSize);

        LambdaQueryWrapper<Course> wrapper = new LambdaQueryWrapper<Course>()
                .eq(Course::getTeacherId, teacherId)
                .like(StringUtils.isNotBlank(courseName), Course::getCourseName, courseName)
                .eq(StringUtils.isNotBlank(status), Course::getStatus, status)
                .orderByDesc(Course::getCreatedTime);

        if (StringUtils.isNotBlank(activityName)) {
            List<Long> activityIds = activityMapper.selectList(
                    new LambdaQueryWrapper<ManagerActivity>()
                            .like(ManagerActivity::getName, activityName)
            ).stream().map(ManagerActivity::getId).collect(Collectors.toList());

            if (!activityIds.isEmpty()) {
                wrapper.in(Course::getActivityId, activityIds);
            }
        }

        IPage<Course> coursePage = courseMapper.selectPage(page, wrapper);

        // 明确指定转换函数的类型
        return coursePage.convert(course -> convertToVO(course));
    }
    @Override
    public boolean saveOrUpdateCourse(CourseDTO courseDTO, Long teacherId) {
        Course course = new Course();
        BeanUtils.copyProperties(courseDTO, course);
        course.setTeacherId(Math.toIntExact(teacherId));

        if (course.getId() == null) {
            course.setCreatedTime(LocalDateTime.now());
            return courseMapper.insert(course) > 0;
        } else {
            // 验证课程是否属于该教师
            Course existingCourse = courseMapper.selectById(course.getId());
            Assert.notNull(existingCourse, "课程不存在");
            Assert.isTrue(existingCourse.getTeacherId().equals(teacherId), "无权修改此课程");

            return courseMapper.updateById(course) > 0;
        }
    }
    @Override
    public boolean deleteTeacherCourse(Long courseId, Long teacherId) {
        return courseMapper.delete(
                new LambdaQueryWrapper<Course>()
                        .eq(Course::getId, courseId)
                        .eq(Course::getTeacherId, teacherId)
        ) > 0;
    }
    @Override
    public boolean updateCourseStatus(Long courseId, String status, Long teacherId) {
        Course course = courseMapper.selectById(courseId);
        Assert.notNull(course, "课程不存在");
        Assert.isTrue(course.getTeacherId().equals(teacherId), "无权修改此课程状态");

        course.setStatus(status);
        return courseMapper.updateById(course) > 0;
    }
    @Override
    public List<StudentVO> getClassStudents(Long classId, Long teacherId) {
        // 验证班级是否属于该教师的课程
        Course course = courseMapper.selectOne(
                new LambdaQueryWrapper<Course>()
                        .eq(Course::getClassId, classId)
                        .eq(Course::getTeacherId, teacherId)
        );
        Assert.notNull(course, "未找到相关班级");

        return classMapper.getClassStudents(classId);
    }

    private CourseVO convertToVO(Course course) {
        CourseVO vo = new CourseVO();
        BeanUtils.copyProperties(course, vo);

        // 获取关联的活动名称
        ManagerActivity activity = activityMapper.selectById(course.getActivityId());
        if (activity != null) {
            vo.setActivityName(activity.getName());
        }

        // 获取关联的班级名称
        ManagerClass classInfo = classMapper.selectById(course.getClassId());
        if (classInfo != null) {
            vo.setClassName(classInfo.getName());
        }

        return vo;
    }

    @Override
    public int countTeacherCourses(Long teacherId) {
        return count(new LambdaQueryWrapper<Course>()
                .eq(Course::getTeacherId, teacherId));
    }

    @Override
    public int countTeacherActiveCourses(Long teacherId) {
        return count(new LambdaQueryWrapper<Course>()
                .eq(Course::getTeacherId, teacherId)
                .eq(Course::getStatus, "1")); // 状态为1表示进行中
    }


}
